<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>推送账户管理</el-breadcrumb-item>
      <el-breadcrumb-item>小时报管理</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form inline class="m-form--filter">
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            multiple
            placeholder="请选择产品名称"
            v-model="filter.productId"
          >
            <el-option
              v-for="(item, index) in productOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            multiple
            filterable
            placeholder="请选择钉钉群"
            v-model="filter.dingId"
          >
            <el-option
              v-for="item in dingOptions"
              :key="item.id"
              :label="item.name"
              :value="item.url"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格操作 -->
      <el-form inline class="m-table--handle">
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="
              $router.push({
                name: 'ding-detail',
                query: {
                  action: 'create',
                },
              })
            "
            >新增</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleClickSetDing" size="mini"
            >配置推送钉钉群</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            @click="
              $router.push({
                name: 'ding-grant'
              })
            "
            size="mini"
            >账号授权方法</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            @click="
              $router.push({
                name: 'ding-push'
              })
            "
            size="mini"
            >非通用模板手动推送</el-button
          >
        </el-form-item>
        <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
        @selection-change="changeTableSelection"
      >
        <el-table-column
          type="selection"
          width="35"
          fixed
          :selectable="handleSelectable"
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
        >
          <template slot-scope="scope">
            <!-- 客户角色 -->
            <template v-if="item.prop === 'customerRole'">{{
              mapOptionLabel(CUSTOMER_ROLE_OPTION, scope.row.customerRole)
            }}</template>
            <template v-else-if="item.prop === 'type'">
              <div v-if="scope.row.type == 1">快手</div>
              <div v-if="scope.row.type == 2">头条</div>
              <div v-if="scope.row.type == 3">头条新平台</div>
            </template>
            <!-- 是否启用 -->
            <template v-else-if="item.prop === 'status'">
              <el-switch
                :width="34"
                :value="scope.row.status"
                :active-value="'0'"
                :inactive-value="'1'"
                @change="
                  changeStatus(
                    scope.row.id,
                    scope.row.status === '0' ? '1' : '0'
                  )
                "
              ></el-switch>
            </template>
            <!-- 其他 -->
            <template v-else>{{ scope.row[item.prop] }}</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <!-- <el-button
              type="text"
              @click="
                $router.push({
                  name: 'flow-account-detail',
                  query: {
                    action: 'edit',
                    id: scope.row.id,
                  },
                })
              "
              >编辑</el-button
            > -->
            <el-button
              type="text"
              @click="
                $router.push({
                  name: 'ding-detail',
                  query: {
                    action: 'detail',
                    id: scope.row.id,
                    editor: '1',
                  },
                })
              "
              >编辑</el-button
            >
            <el-button type="text" @click="fetch(scope.row.id)" v-if="scope.row.status == '0'"
              >手动推送</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="[500]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="pageTotal"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
    </Container>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import moment from "moment";

import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";
import Tip from "@/components/tip";
import ImportTable from "@/components/import-table.vue";

import { exportExcel } from "@/utils/fileDown.js";
import { OPERATOR_OPTION, CUSTOMER_ROLE_OPTION } from "@/assets/js/flow-option";
import { mapOptionLabel } from "@/util";

export default {
  name: "flow-account",
  components: {
    Container,
    CustomTableColumn,
    Tip,
    ImportTable,
  },
  data() {
    return {
      OPERATOR_OPTION,
      CUSTOMER_ROLE_OPTION,

      // 下拉
      customerOptions: [],
      platformOptions: [],
      usernameOptions: [],

      productOptions: [],
      dingOptions: [],

      // 筛选
      filter: {
        customerId: Number(this.$route.query.customerId) || null,
        productId: Number(this.$route.query.productId) || null,
        platformId: Number(this.$route.query.platformId) || null,
        usernameId: [null],
        operator: null,
        dingId: null,
        productId: null,
      },

      // 导入
      importName: "导入",
      importUrl: "/manage/api/bus/account/import_account",

      // 运营方式
      dialogOperateVisible: false,
      dialogOperateData: {
        operate: [],
      },
      dialogOperateRules: {
        operator: {
          required: true,
          message: "请选择运营方式",
          trigger: ["blur", "change"],
        },
      },

      tableData: [],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "产品名称",
          prop: "productName",
          visible: true,
        },
        {
          label: "推送模板",
          prop: "type",
          visible: true,
        },
        {
          label: "返点",
          prop: "factor",
          visible: true,
        },
        {
          label: "推送钉钉群",
          prop: "dingName",
          visible: true,
        },
        {
          label: "开始推送日期",
          prop: "ctime",
          visible: true,
        },
        {
          label: "推送状态",
          prop: "status",
          visible: true,
        },
      ],
      page: {
        pageNo: 1,
        pageSize: 500,
      },
      pageTotal: 0,
    };
  },
  computed: {
    requestSearch() {
      return {
        //  ...this.filter,
        customerId: null,
        productId: null,
        platformId: null,
        operator: null,
        ...this.page,
        usernameId: this.filter.usernameId.includes(null)
          ? null
          : this.filter.usernameId.join(),
      };
    },
    filterTableColumn() {
      return this.tableColumn.filter((item) => item.visible);
    },
    // 运营人日期不可重复
    dialogOperatePickerOptions() {
      let vm = this;
      return {
        disabledDate(date) {
          return vm.dialogOperateData.operate.some((item) => {
            return item.startDate === moment(date).format("YYYY-MM-DD");
          });
        },
      };
    },
  },
  methods: {
    mapOptionLabel,
    exportExcel,
    fetch(id) {
      this.$http({
        method: "get",
        url: "/marketing/api/daily/fetch/all",
        params: {
          id: id,
        },
      })
        .then((res) => {
          if (res.data.code === 1) {
            this.$message.success("已推送群里，请查看对应钉钉群。若无数据展示，请先确认账户是否授权。");
          }
        })
        .catch((err) => {
          this.$message.error("手动推送失败");
        });
    },
    handleClickSetDing() {
      console.log(this.tableSelectionData);
      if (this.tableSelectionData.length == 0) {
        this.$message.error("请选择要配置推送钉钉群的产品");
        return;
      }
      this.$router.push({
        name: "ding-set",
        query: {
          action: "set",
          ids: this.tableSelectionData.map((item) => item.id).join(),
        },
      });
    },
    handleClickPush() {
      this.$message({
        message: "推送成功",
        type: "success",
      });
      // 手动推动
      // this.$http({
      //   method: "get",
      //   url: "/manage/api/bus/customer/get_customer_name",
      //   params: {
      //     status: 0
      //   }
      // }).then(res => {
      //   if (res.data.code === 0) {
      //     this.$message({
      //       message: '推送成功',
      //       type: 'success'
      //     });
      //   }else{
      //     this.$message.error('推送失败,请重新推送');
      //   }
      // });
    },
    // 下载模板
    downloadTemplate() {
      location.href = "https://s.55duanzi.com/CMS/账号管理导入表格.xls";
    },
    // 下拉
    fetchDingOptions() {
      this.$http({
        method: "get",
        url: "/marketing/api/daily/getDingList",
      }).then((res) => {
        if (res.data.code === 1) {
          this.dingOptions = res.data.data;
          /* if (this.$route.query.dingId) {
            this.filter.dingId = Number(this.$route.query.dingId);
          } */
        }
      });
    },
    fetchProductOptions() {
      this.$http({
        method: "get",
        url: "/marketing/api/daily/getProductList",
      }).then((res) => {
        if (res.data.code === 1) {
          this.productOptions = res.data.data;
          /* if (this.$route.query.productId) {
            this.filter.productId = Number(this.$route.query.productId);
          } */
        }
      });
    },

    // 下拉框回显
    getCurrentOperate(data = []) {
      let len = data.length;
      if (len) {
        let item = data[len - 1];
        return `${item.operatorBy}`;
      }
      return "-";
    },

    // 列表
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    getTable() {
      this.$http({
        method: "get",
        url: "/marketing/api/daily/getList",
        params: {
          curpage: this.page.pageNo,
          limit: this.page.pageSize,
          product: this.filter.productId.join(),
          dingUrl: this.filter.dingId.join(),
        },
      }).then((res) => {
        if (res.data.code === 1) {
          let data = res.data.data;
          this.tableData = data.list;
          this.pageTotal = data.listCount;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    multiChangeState(action) {
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要操作的选项！");
      }
      this.changeStatus(
        this.tableSelectionData.map((item) => item.id).join(),
        action
      );
    },
    changeStatus(id, status) {
      this.$http({
        method: "get",
        url: "/marketing/api/daily/status",
        params: {
          id: id,
          status,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.$message.success(`推送状态更改成功`);
          this.getTable();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleDelete(id) {
      this.$confirm("是否删除此账号？删除后不可恢复！", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            method: "post",
            url: "/manage/api/bus/account/del",
            params: {
              ids: id,
            },
          }).then((res) => {
            if (res.data.code === 0) {
              this.$message.success("删除成功!");
              this.getTable();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
    removeAccount() {
      this.$confirm("是否删除此账号？删除后不可恢复！", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {})
        .catch(() => {});
    },
    handleSelectable() {
      return true;
    },
    changeTableSelection(data) {
      this.tableSelectionData = data;
      //id =  this.tableSelectionData.map(item => item.id).join()
    },
    handlePagerSizeChange(v) {
      this.page.pageSize = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.page.pageNo = v;
      this.getTable();
    },
  },
  activated() {
    // 筛选
    if (this.$route.query.customerId) {
      this.filter = {
        customerId: Number(this.$route.query.customerId) || null,
        productId: Number(this.$route.query.productId) || null,
        platformId: Number(this.$route.query.platformId) || null,
        usernameId: [null],
        operator: null,
      };
    }
    this.getTable();
  },
  created() {
    this.fetchDingOptions();
    this.fetchProductOptions();
  },
};
</script>